package com.ys.zero.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.ys.zero.bean.Dict;
import com.ys.zero.bean.Uarticle;
import com.ys.zero.bean.User;
import com.ys.zero.util.DBHelper;

/**
 * 搜索Dao
 * @author Administrator
 *
 */
public class SearchDao {
	
	/**
	 * 首页搜索
	 * @param keyword
	 * @return
	 */
	public List<Uarticle> seaech(String keyword) {
		String sql = "select a.* from uarticle a join user b on b.id=a.uid";
		List<Object> params = new ArrayList<>();
		sql += " where a.utitle like ? or a.log like ?";
		params.add("%"+keyword+"%");
		params.add("%"+keyword+"%");
		String sql1 = "update dict set log_count=log_count+1 where log in (select DISTINCT log from uarticle";
		sql1 +=" where utitle like ?  or log like ?)";
		List<Object> params1 = new ArrayList<>();
		params1.add("%"+keyword+"%");
		params1.add("%"+keyword+"%");
		List<Uarticle> list = null;
		try {
			list = DBHelper.query(sql,Uarticle.class,params.get(0).toString(),params.get(1).toString());
			DBHelper.update(sql1,params1.get(0).toString(),params.get(1).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	
	/**
	 * 显示大家都在搜
	 * @return
	 */
	public List<Uarticle> showLog() {
		String sql = "select b.uaid,b.utitle from dict a join uarticle b on a.log=b.log order by a.log_count desc LIMIT 0,16";
		return DBHelper.query(sql,Uarticle.class);
	}
	
	
	
	/**
	 * 显示搜索结果+分页
	 * @param log
	 * @param pageIndex 当前页码
	 * @return
//	 */
	public List<Uarticle> showSearch(String log,int pageIndex) {
		String sql = "select b.* from uarticle b";
		List<Object> params = new ArrayList<>();
		sql += " where b.utitle like ? or b.log like ? order by b.visit desc limit ?,5";
		params.add("%"+log+"%");
		params.add("%"+log+"%");
		params.add((pageIndex-1)*5);
		return DBHelper.query(sql,Uarticle.class,params.get(0).toString(),params.get(1).toString(),params.get(2));
	}
	/**
	 * 得到搜索文章数量
	 * @param log
	 * @return
	 */
	public Object getCount(String log) {
		String sql = "select count(*) from uarticle";
		List<Object> params = new ArrayList<>();
		sql += " where utitle like ? or log like ?";
		params.add("%"+log+"%");
		params.add("%"+log+"%");
		return DBHelper.queryValue(sql,params.get(0).toString(),params.get(1).toString());
	}
	
	/**
	 * 得到创作人的名字
	 * @param log
	 * @return
	 */
	public List<User> getName(String log) {
		String sql = "select b.id,b.`name`,b.image from uarticle a join user b on a.uid=b.id";
		List<Object> params = new ArrayList<>();
		sql += " where a.utitle like ? or a.log like ?  order by a.visit desc";
		params.add("%"+log+"%");
		params.add("%"+log+"%");
		return DBHelper.query(sql,User.class,params.get(0).toString(),params.get(1).toString());
	}
	
	
}
